#!/bin/bash
# Author: Narunas Krasauskas
# Installer script for kvm-init.sh

if which sudo &> /dev/null; then
    _su=$(which sudo) && export _su
    $_su cat /dev/null &> /dev/null
elif [ $(id -ur) -eq 0 ]; then
    _su='' && export _su
else
    echo "Please run as \`root' user!"
    exit 1
fi


if test -f /etc/qemu-ifup; then
    echo -e '\n(1/2) : Installing new qemu-ifup rules:\n'; sleep 1 
    $_su cp -vf /etc/qemu-ifup{,.bak} &&\
    $_su rm -vf /etc/qemu-ifup || exit 1 
    grep -iq libvirt-qemu /etc/group || $_su addgroup --system --debug libvirt-qemu
    $_su install -vo root -g libvirt-qemu -m 755 ./qemu-ifup /etc/qemu-ifup
    echo '(2/2) : Backup of previous qemu-ifup rules is placed at /etc/qemu-ifup.bak'; sleep 1
fi
if test -f /etc/qemu-ifdown; then
    echo -e '\n(1/2) : Installing new qemu-ifdown rules:\n'; sleep 1 
    $_su cp -vf /etc/qemu-ifdown{,.bak} &&\
    $_su rm -vf /etc/qemu-ifdown || exit 1 
    grep -iq libvirt-qemu /etc/group || $_su addgroup --system --debug libvirt-qemu
    $_su install -vo root -g libvirt-qemu -m 755 ./qemu-ifdown /etc/qemu-ifdown
    echo '(2/2) : Backup of previous qemu-ifdown rules is placed at /etc/qemu-ifdown.bak'; sleep 1
fi
if test ! -f /etc/qemu-ifup -a ! -f /etc/qemu-ifdown; then
    echo -e '\nInstalling new qemu-ifdupdown rules:\n'; sleep 1
    grep -iq libvirt-qemu /etc/group || $_su addgroup --system --debug libvirt-qemu
    $_su install -vo root -g libvirt-qemu -m 755 ./qemu-ifup /etc/qemu-ifup
    $_su install -vo root -g libvirt-qemu -m 755 ./qemu-ifdown /etc/qemu-ifdown
fi
